package com.github.cyf.config.satoken;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.github.cyf.domain.po.Permission;
import com.github.cyf.domain.po.Role;
import com.github.cyf.service.PermissionService;
import com.github.cyf.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenyifan
 * @create 2024-10-28 10:46
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleService roleService;

    /**
     * 返回指定账号id所拥有的权限码集合
     *
     * @param loginId  账号id
     * @param loginType 账号类型
     * @return 该账号id具有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> codes = StpUtil.getSession().getModel(SaSession.PERMISSION_LIST, List.class);
        if (!CollectionUtils.isEmpty(codes)) {
            return codes;
        }
        List<Permission> permissions = permissionService.queryPermissionByUserId(Long.valueOf(loginId.toString()));
        return permissions.stream().map(Permission::getPermissionValue).collect(Collectors.toList());
    }

    /**
     * 返回指定账号id所拥有的角色标识集合
     *
     * @param loginId  账号id
     * @param loginType 账号类型
     * @return 该账号id具有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> codes = StpUtil.getSession().getModel(SaSession.ROLE_LIST, List.class);
        if (!CollectionUtils.isEmpty(codes)) {
            return codes;
        }
        List<Role> roles = roleService.queryRoleByUserId(Long.valueOf(loginId.toString()));
        return roles.stream().map(Role::getRoleCode).collect(Collectors.toList());
    }
}